package service

import (
	"bytes"
	"context"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"server/global"

	"github.com/jinzhu/gorm"
)

type Service struct {
	ctx    context.Context
	engine *gorm.DB
}

func New(ctx context.Context) *Service {
	return &Service{ctx: ctx, engine: global.DBEngine}
}

func (svc *Service) Request(chainName, path string, form map[string]interface{}) (map[string]interface{}, error) {
	body, err := json.Marshal(form)
	if err != nil {
		return nil, err
	}

	reader := bytes.NewReader(body)

	resp, err := http.Post(global.GetChainAddr(chainName)+path, "application/json;charset=utf-8", reader)
	if err != nil {
		return nil, err
	}

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	res := make(map[string]interface{})
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		return nil, err
	}

	return res, nil
}
